package com.by.zhdoctor.web.rest;

import com.codahale.metrics.annotation.Timed;
import com.by.zhdoctor.domain.RuleRepository;

import com.by.zhdoctor.repository.RuleRepositoryRepository;
import com.by.zhdoctor.web.rest.util.HeaderUtil;
import com.by.zhdoctor.web.rest.util.PaginationUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.support.HttpRequestHandlerServlet;

import javax.inject.Inject;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;

/**
 * REST controller for managing RuleRepository.
 */
@RestController
@RequestMapping("/api")
public class RuleRepositoryResource {

    private final Logger log = LoggerFactory.getLogger(RuleRepositoryResource.class);

    @Inject
    private RuleRepositoryRepository ruleRepositoryRepository;

    /**
     * POST  /rule-repositories : Create a new ruleRepository.
     *
     * @param ruleRepository the ruleRepository to create
     * @return the ResponseEntity with status 201 (Created) and with body the new ruleRepository, or with status 400 (Bad Request) if the ruleRepository has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/rule-repositories")
    @Timed
    public ResponseEntity<RuleRepository> createRuleRepository(@RequestBody RuleRepository ruleRepository) throws URISyntaxException {
        log.debug("REST request to save RuleRepository : {}", ruleRepository);
        if (ruleRepository.getId() != null) {
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("ruleRepository", "idexists", "A new ruleRepository cannot already have an ID")).body(null);
        }
        RuleRepository result = ruleRepositoryRepository.save(ruleRepository);
        return ResponseEntity.created(new URI("/api/rule-repositories/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert("ruleRepository", result.getId().toString()))
            .body(result);
    }

    /**
     * PUT  /rule-repositories : Updates an existing ruleRepository.
     *
     * @param ruleRepository the ruleRepository to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated ruleRepository,
     * or with status 400 (Bad Request) if the ruleRepository is not valid,
     * or with status 500 (Internal Server Error) if the ruleRepository couldnt be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/rule-repositories")
    @Timed
    public ResponseEntity<RuleRepository> updateRuleRepository(@RequestBody RuleRepository ruleRepository) throws URISyntaxException {
        log.debug("REST request to update RuleRepository : {}", ruleRepository);
        if (ruleRepository.getId() == null) {
            return createRuleRepository(ruleRepository);
        }
        RuleRepository result = ruleRepositoryRepository.save(ruleRepository);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert("ruleRepository", ruleRepository.getId().toString()))
            .body(result);
    }

    /**
     * GET  /rule-repositories : get all the ruleRepositories.
     *
     * @param pageable the pagination information
     * @return the ResponseEntity with status 200 (OK) and the list of ruleRepositories in body
     * @throws URISyntaxException if there is an error to generate the pagination HTTP headers
     */
    @GetMapping("/rule-repositories")
    @Timed
    public ResponseEntity<List<RuleRepository>> getAllRuleRepositories(Pageable pageable)
        throws URISyntaxException {
        log.debug("REST request to get a page of RuleRepositories");
        Page<RuleRepository> page = ruleRepositoryRepository.findAll(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/rule-repositories");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }

    /**
     * GET  /rule-repositories/:id : get the "id" ruleRepository.
     *
     * @param id the id of the ruleRepository to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the ruleRepository, or with status 404 (Not Found)
     */
    @GetMapping("/rule-repositories/{id}")
    @Timed
    public ResponseEntity<RuleRepository> getRuleRepository(@PathVariable Long id) {
        log.debug("REST request to get RuleRepository : {}", id);
        RuleRepository ruleRepository = ruleRepositoryRepository.findOne(id);
        return Optional.ofNullable(ruleRepository)
            .map(result -> new ResponseEntity<>(
                result,
                HttpStatus.OK))
            .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    /**
     * DELETE  /rule-repositories/:id : delete the "id" ruleRepository.
     *
     * @param id the id of the ruleRepository to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/rule-repositories/{id}")
    @Timed
    public ResponseEntity<Void> deleteRuleRepository(@PathVariable Long id) {
        log.debug("REST request to delete RuleRepository : {}", id);
        ruleRepositoryRepository.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert("ruleRepository", id.toString())).build();
    }

    /**
     * GET  /rule-repositories/:bm : get the "bmName" ruleRepository.
     *
     * @param bmName the id of the ruleRepository to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the ruleRepository, or with status 404 (Not Found)
     */
    @GetMapping("/rule-repositories-docterlist/{bmName}")
    @Timed
    public ResponseEntity<List<RuleRepository>> getRuleRepositoryDocterlist(@PathVariable String bmName) {
        log.debug("REST request to get RuleRepository : {}", bmName);
        List<RuleRepository> ruleRepository = ruleRepositoryRepository.findDocterNameListByBMName(bmName);
        return Optional.ofNullable(ruleRepository)
            .map(result -> new ResponseEntity<>(
                result,
                HttpStatus.OK))
            .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }
    /**
     * GET  /rrule-repositories-listBydoctor/:bm/:dtName : get the "bmName & dtName" ruleRepository.
     *
     * @param bmName the id of the ruleRepository to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the ruleRepository, or with status 404 (Not Found)
     */
    @GetMapping("/rule-repositories-listBydoctor/{bmName}/{dtName}")
    @Timed
    public ResponseEntity<List<RuleRepository>> getRuleRepositoryListByDoctor(@PathVariable String bmName,@PathVariable String dtName) {
        log.debug("REST request to get RuleRepository : {}", bmName,dtName);
        List<RuleRepository> ruleRepository = ruleRepositoryRepository.findByBingmingNameAndDoctorName(bmName,dtName);
        return Optional.ofNullable(ruleRepository)
            .map(result -> new ResponseEntity<>(
                result,
                HttpStatus.OK))
            .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }
    /**
     * GET  /rrule-repositories-listBydoctor get the " dtName" ruleRepository.
     *
     * @param dtName the id of the ruleRepository to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the ruleRepository, or with status 404 (Not Found)
     */
    @GetMapping("/rule-repositoriesDataByDoctor")
    @Timed
    public ResponseEntity<List<RuleRepository>> getRuleRepositoriesDataByDoctor(HttpServletRequest httpServletRequest, Pageable pageable) throws URISyntaxException {

        log.debug("REST request to get RuleRepository : {}");
        String dtName=httpServletRequest.getParameter("name");
        Page<RuleRepository> ruleRepository = ruleRepositoryRepository.findByDoctorName(dtName,pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ruleRepository, "/api/rule-repositoriesDataByDoctor");
        return new ResponseEntity<>(ruleRepository.getContent(), headers, HttpStatus.OK);
    }
}
